<template>
<!-- 商铺广告 -->
  <div id="Administration">
    <div id="managements">
      <!--搜索框 -->
      <div id="manage-top">
        <el-select v-model="allPages.status" clearable placeholder="请输入广告类型">
          <el-option
            style="height:46px"
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="allPages.adType" clearable placeholder="请输入广告状态">
          <el-option
            style="height:46px"
            v-for="item in adType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <button type="button" class="el-button el-button--primary" @click="management()">
          <i class="el-icon-search"></i>
          <span>查找</span>
        </button>
        <button type="button" class="el-button el-button--primary" @click="additions()"  v-Promise="'promote:advertisement:create'">
          <i class="el-icon-edit"></i>
          <span>添加</span>
        </button>
      </div>
      <!-- 数据操作 -->
      <div id="manage-bottom">
        <el-table
          border
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          :key="id"
        >
          <el-table-column label="广告ID" prop="id"></el-table-column>
          <el-table-column label="广告标题" prop="title"></el-table-column>
          <el-table-column label="广告类型" prop="adType">
            <template slot-scope="scope">
                <el-tag>{{scope.row.adType|adTypes()}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="广告状态" prop="status" >
            <template slot-scope="scope">
              <el-tag>{{scope.row.status|status()}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="广告图片" prop="imgUrl">
            <template slot-scope="scope">
                <img :src="scope.row.imgUrl" style="height:40px">
            </template>
          </el-table-column>
          <el-table-column label="广告活动" prop="url"></el-table-column>
          <el-table-column align="right" label="操作" width="250px;">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="compile(scope.$index,scope.row)"
                class="kohlrabiblue"
                v-Promise="'promote:advertisement:update'"
              >编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)" v-Promise="'promote:advertisement:delete'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <Paging @handle="handles" :allPages="allPages"></Paging>
      </div>
      <div>
        <!-- 添加编辑弹框 -->
        <el-dialog :title="titleName" :visible.sync="dialogFormVisible">
          <div class="loginRight">
            <div class="login-right">
              <el-form
                :model="ruleForm"
                status-icon
                ref="ruleForm"
                :rules="rules"
                label-width="100px"
                class="demo-ruleForm"
              >
                <!-- 广告标题 -->
                <el-form-item prop="title" label="广告标题">
                  <el-input v-model.number="ruleForm.title"></el-input>
                </el-form-item>
                <!-- 上传 -->
                <div class="uploading">
                  <div class="uptitle">
                      <span>广告图片</span>
                    </div>
                     <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </div>
                <!-- 广告类型 -->
                <el-form-item label="广告类型">
                  <el-select v-model="ruleForm.adType">
                    <el-option
                        style="height:46px"
                        v-for="item in adType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 广告状态 -->
                <el-form-item label="广告状态">
                  <el-select v-model="ruleForm.status">
                    <el-option
                        style="height:46px"
                        v-for="item in status"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 关联1 -->
                <el-form-item label="关联1">
                  <el-cascader v-model="cascades" :options="spuTitl" :props="{ checkStrictly: true,value:'id',label:'label' }" 
                   @change="relevance"></el-cascader>
                </el-form-item>   
                 <!-- 关联2 -->
                <el-form-item label="关联2">
                  <el-select v-model="ruleForm.group"  @change="relevance2">
                    <el-option                
                        style="height:46px"
                        v-for="item in group"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>       
              </el-form>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="affirm()">
              <div>确 定</div>
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import shopadv from "@/api/shopadvert.js";
import Paging from "../../components/Paging"; //分页
import qs from "qs";
export default {
  components: {
    Paging
  },
  data() {
    //   优惠卷名称
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("广告标题不能为空！"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: '',//上传
      radio1: "领券相对天数",
      radio2: "全场通用",
      spuTitl: [],
      looktitle: "",
      adType: [
        {
          value: 1,
          label: "轮播"
        },
         {
          value: 2,
          label: "分类精选"
        },
         {
          value: 3,
          label: "横幅"
        },
         {
          value: 4,
          label: "首页轮播下5按钮"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      status: [
        {
          value: 0,
          label: "冻结"
        },
        {
          value: 1,
          label: "激活"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      group:[
          {
           value: null,
           label: "团购列表"
          }
      ],
      id: "",
      cascades: "",
      search: "",
      titleName: "", //是否添加还是编辑
      tableData: [{}],
      dialogFormVisible: false, //弹窗口
      totalPageNo: 1,
      value1: [],
      allPages: {
        currentPage: 1, //当前的默认的页数
        eachpage: 10, //默认的页码
        total: 0, //初始值共数据条
        totalPageNo: 1,
        // 查询
        value: "",
        // 优惠券
        title: "",
        type: "",
        description: "",
        surplus: "",
        limit: "",
        discount: "",
        min: "",
        status: "",
        adType :"",
      }, //分页
      ruleForm: {
        title:"",
        status:"",
        color :"",
        adId :"",
        adType:"",
        id:''
      },
      rules: {
        title: [
          {
            validator: checkAge,
            trigger: "blur"
          }
        ]
      }
    };
  },
  //时间戳
  filters: {
    adTypes: function(value) {
        switch(value) {
         case 0:
            value='首页轮播下5按钮'
            break;
        case 1:
            value='轮播'
            break;
        case 2:
            value='分类精选'
            break;
        case 3:
            value='横幅'
            break;
        case 4:
            value='首页轮播下5按钮'
            break;
       } 
     return value
    },
    status: function(value) {
      return value == 0 ? "冻结" : "激活";
    }
  },
  methods: {
    // 
    relevance(){
      // console.log(typeof this.cascades)
      // this.ruleForm.group=""
      // if (this.cascades.length<3) {
      //    this.$information.error('请关联第三级类目或者商品')
      // }else{
        
      // }
    },
    relevance2(){
     this.cascades=""
    },
    // 上 传
       handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
    // 编辑
    compile(index, row) {
      this.forbidden = true;
      this.dialogFormVisible = true;
      this.titleName = "查看";
      this.modalType = "update";
      this.ruleForm = { ...row };
      this.imageUrl=row.imgUrl
      // console.log(typeof this.cascades)
      if (row.url.indexOf("id")==-1) {
       this.cascades = "";
      console.log(111)
      }else{
        this.cascades = Number(row.url.split("=")[1]);
        console.log(Number(row.url.split("=")[1]))
      }
    },
    //添加
    additions() {
      this.forbidden = false;
      this.titleName = "创建";
      this.modalType = "add";
      this.dialogFormVisible = true;
      this.ruleForm = {};
      this.imageUrl=""
    },
    // 分页负值
    handles(val) {
      this.allPages = val;
      this.management();
    },
    // 管理员数据列表
    management() {
      let _this = this;
      shopadv.discount(_this.allPages).then(function(res) {
        console.log(res);
        _this.tableData = res.data.data.items;
        _this.ruleForm = {...res.data.data.items};
        // 分页
        _this.allPages.currentPage = res.data.data.pageNo;
        _this.allPages.eachpage = res.data.data.pageSize;
        _this.allPages.total = res.data.data.total;
        _this.allPages.totalPageNo = res.data.data.totalPageNo;
      });
    },
      // 递归
      getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].children.length<1){
          // children若为空数组，则将children设为undefined
          data[i].children=undefined;
        }else {
          if (data[i].children.length==3) {
             data[i].children=undefined;
          }else{
             // children若不为空数组，则继续 递归调用 本方法
              this.getTreeData(data[i].children);
          }
         
        }
      }
      return data;
    },
     // sup树
    supshu() {
        let _this=this;
      shopadv.spuTitles().then(res => {
        _this.spuTitl =_this.getTreeData(res.data.data)
      });
    },
        // 删除
        handleDelete(index, row) {
          var _this = this;
           //   提示框
          _this.$confirm("此操作将永久删除, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
            .then(() => {
              _this.$information.success('删除成功')
              let data = {
                id: _this.tableData[index].id,
                adType:row.adType
              };
              shopadv.handleDeletec(data).then(function(res) {
                _this.tableData.splice(index, 1);
              });
            });
        },
        affirm() {
                 console.log(this.ruleForm.url,this.ruleForm.color) 
          let _this = this;
          //添加
          if (_this.titleName === "创建") {
            shopadv.addition(_this.ruleForm,_this.imageUrl).then(function(res) {
              console.log(res.data)
              if (res.data.errmsg == "成功") {
                 _this.management()
                   _this.dialogFormVisible = false;
                _this.$information.success('这是一条添加成功的提示消息')
              } else {
                 _this.$information.error('这是一条添加失败的提示消息')
              }
            });
          }
        //   编辑
          if (_this.titleName === "查看") {
            shopadv.compile(_this.ruleForm,_this.imageUrl,_this.cascades).then(function(res) {
                   console.log(res)
                if (res.data.errmsg == "成功") {          
                     _this.$information.success('这是一条编辑成功的提示消息')
                    _this.management()
                      _this.dialogFormVisible = false;
                }else{
                    _this.$information.error('这是一条编辑失败的提示消息')
                }
            });
          }
        }
  },
  created() {
    this.management();
    this.supshu(); //sup树
  },
  watch:{
    dialogFormVisible(){
      this.$nextTick(() => {
       this.$refs.ruleForm.clearValidate();
      })
    }
  }
};
</script>

<style scoped>
#Administration {
  width: 100%;
  height: 100%;
}
#Administration ::-webkit-scrollbar {
  width: 0px !important;
}
#managements {
  width: 80vw;
  height: 80vh;
  margin: auto;
}
/* 搜索框 */
#manage-top {
  width: 100vw;
  display: flex;
  margin-bottom: 30px;
}
#manage-top .el-input__inner {
  width: 200px;
}
.el-input {
  width: 210px;
}

/* 表格样式*/
#block {
  margin-top: 30px;
}
.kohlrabiblue {
  background: #66b1ff;
  color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
  text-align: center;
}
.el-table/deep/th.is-sortable {
  cursor: pointer;
  text-align: center;
}
.el-table td,
.el-table/deep/th.is-leaf {
  text-align: center;
}
/*  */
.loginRight {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 0px 8px 8px 0px;
}
.login-right {
  width: 80%;
  margin: auto;
}
.loginRight .login-title {
  color: #333;
  margin-bottom: 40px;
  font-weight: 500;
  font-size: 22px;
  text-align: center;
  letter-spacing: 4px;
  margin-top: 40px;
}
.el-form-item/deep/input {
  background: transparent;
  border-radius: 0;
  color: #333;
  display: inline;
}
.el-form-item {
  height: 50px !important;
  position: relative;
}
.el-form-item/deep/i {
  display: inline;
}
.impose {
  padding-top: 40px;
  position: relative;
}
.poke {
  position: absolute;
  top: 55px;
  left: -102px;
}
.el-checkbox {
  width: 300px;
  margin: 20px 0px 30px 0px;
}
/* 弹出框 */
.el-input-group__append {
  position: relative;
  top: -40px;
  left: 210px;
}
#deadline {
  position: relative;
}
.time {
  position: absolute;
  top: 42px;
  left: 0px;
}
.el-form-item__content {
  height: 10px;
}
/* 上传 */
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #409EFF;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .uploading{
    margin-left:30px;
    margin-bottom: 20px;
  }
  .uploading span{
    height: 0px ;
    color: #606266;
  }
  .avatar-uploader{
    margin-left:100px;
  }
  .uptitle{
    height: 0px;
  }
</style>